<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\logic\BaseLogic;
use app\common\model\user\User;
use app\common\model\card\Card;
use app\common\model\finance\TransactionRecord;
use think\facade\Db;


/**
 * card逻辑
 * Class CardTagLogic
 * @package app\api\logic
 */
class DashboardLogic extends BaseLogic
{


    /**
     * @notes 添加card
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/09 19:15
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            CardTag::create([
                'name' => $params['name'],
                'user_id' => $params['user_id'],
                'sort' => $params['sort'] ?? 0
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑card
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/09 19:15
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {

            CardTag::update([
                'name' => $params['name'],
                'update_time' => time()
            ], ['id' => $params['id'], 'user_id' => $params['user_id']]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    public static function index(array $params): array
    {
        $activeCard = Card::where('group_id', $params['group_id'])->where('status', 1)->count();
        $userCount = User::where('group_id', $params['group_id'])->count();
        $totalConsumption = TransactionRecord::where('group_id', $params['group_id'])
            ->whereDay('transaction_date', 'today')
            ->whereIn('transaction_type', ['CARD_PAYMENT', 'CLEARING', 'settled', 'pending', 'AUTHORIZATION', 'WAITING_CLEARANCE'])
            ->whereRaw("RTRIM(LTRIM(status)) IN ('SUCCESS', 'CANCELLED', 'settled', 'posted', 'pending', 'CARD_PAYMENT', 'WAITING_CLEARANCE')")
            ->sum('billing_amount');

        return [
            'active_cards_count' => $activeCard,
            'total_consumption' => abs($totalConsumption),
            'user_count' => $userCount,
        ];

    }


//    主页消费数据
    public static function dailySpend(array $params): array
    {
        $where['group_id'] = $params['group_id'];
        // 成功交易类型条件

        // 隐藏 user_id 条件，注释掉关键词搜索
        // if (isset($params['keyword'])) {
        //     $id = User::where('account|email', $params['keyword'])->value('id');
        //     $where['user_id'] = $id ?? 0;
        // }

        $list = TransactionRecord::field([
            'DATE_FORMAT(transaction_date, "%Y-%m-%d") as transaction_date',
            'ABS(SUM(billing_amount)) as billing_amount'
        ])
            ->whereTime('transaction_date', 'between', $params['between_time'])
            ->whereIn('transaction_type', ['CARD_PAYMENT', 'CLEARING', 'settled', 'pending', 'AUTHORIZATION', 'WAITING_CLEARANCE'])
            ->whereRaw("RTRIM(LTRIM(status)) IN ('SUCCESS', 'CANCELLED', 'settled', 'posted', 'pending', 'CARD_PAYMENT', 'WAITING_CLEARANCE')")
            ->where($where)
            ->group('DATE_FORMAT(transaction_date, "%Y-%m-%d")') // 按年月分组
            ->order('transaction_date') // 按年月排序
            ->select()
            ->toArray();
        foreach ($list as &$item) {
            $item['billing_amount'] = (float)$item['billing_amount'];
        }

        //计算service_amount的总和和平均数
        $totalBillingAmount = array_sum(array_column($list, 'billing_amount'));
        $averageBillingAmount = count($list) > 0 ? $totalBillingAmount / count($list) : 0;

        return [
            'total_spend' => (float)number_format($totalBillingAmount, 2, '.', ''),
            'avg_spend' => (float)number_format($averageBillingAmount, 2, '.', ''),
            'list' => $list
        ];
    }

//    主页拒付比例
    public static function declinedRate(array $params): array
    {


        $where['group_id'] = $params['group_id'];
        // 隐藏 user_id 条件，注释掉关键词搜索
        // if (isset($params['keyword'])) {
        //     $id = User::where('account|email', $params['keyword'])->value('id');
        //     $where['user_id'] = $id ?? 0;
        // }

        $list = TransactionRecord::field([
            'DATE_FORMAT(transaction_date, "%Y-%m-%d") as transaction_date',
            //拒付比例，即status=DECLINE占有的比例
            'SUM(CASE WHEN transaction_type IN ("declined","CARD_PAYMENT") AND status IN ("failed","CANCELLED") THEN 1 ELSE 0 END) / COUNT(*) as decline_rate',
            'SUM(CASE WHEN transaction_type IN ("CARD_PAYMENT", "CLEARING", "settled", "pending", "AUTHORIZATION", "WAITING_CLEARANCE") AND RTRIM(LTRIM(status)) IN ("SUCCESS", "CANCELLED", "settled", "posted", "pending", "CARD_PAYMENT", "WAITING_CLEARANCE") THEN 1 ELSE 0 END) / COUNT(*) as success_rate'
        ])
            ->whereTime('transaction_date', 'between', $params['between_time'])
            ->where($where)
            ->group('DATE_FORMAT(transaction_date, "%Y-%m-%d")') // 按年月分组
            ->order('transaction_date') // 按年月排序
            ->select()
            ->toArray();

        //计算decline_rate的平均数
        $totalDeclineRate = array_sum(array_column($list, 'decline_rate'));
        $averageDeclineRate = count($list) > 0 ? $totalDeclineRate / count($list) : 0;

        //计算success_rate的平均数
        $totalSuccessRate = array_sum(array_column($list, 'success_rate'));
        $averageSuccessRate = count($list) > 0 ? $totalSuccessRate / count($list) : 0;

        return [
            'avg_decline_rate' => number_format($averageDeclineRate, 2, '.', ''),
            'success_decline_rate' => number_format($averageSuccessRate, 2, '.', ''),
            'list' => $list
        ];
    }

}

